package com.zr.service.order.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zr.dao.order.OrderFeeDao;
import com.zr.dao.order.OrderFormDao;
import com.zr.dao.order.OrderGoodsDao;
import com.zr.exception.BusinessException;
import com.zr.service.order.OrderFormService;
import com.zr.utils.SequenceUtil;
import com.zr.vo.order.OrderForm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import static com.zr.service.car.impl.CarServiceImpl.getImgBase;

/**
 * 委托订单处理
 *
 */
@Service
public class OrderFormServiceImpl implements OrderFormService {

    @Resource
    private OrderFormDao orderFormDao;

    @Resource
    private OrderFeeDao orderFeeDao;

    @Resource
    private OrderGoodsDao orderGoodsDao;

    @Resource
    private SequenceUtil sequenceUtil;

    // 注入订单编号前缀
    @Value("${orderId.prefix}")
    private String orderIdPrefix;

    // 注入图片存储路径
    @Value("${img.path}")
    private  String imgPath;

    /**
     * 条件查询委托订单列表
     * @param orderForm
     * @return PageInfo<OrderForm>
     * @author huangguilong
     */
    @Override
    public PageInfo<OrderForm> list(OrderForm orderForm) {
        PageHelper.startPage(orderForm.getPageNum(), orderForm.getPageSize());
        List<OrderForm> orderFormList = orderFormDao.list(orderForm);
        return new PageInfo<OrderForm>(orderFormList);
    }

    /**
     * 新增委托订单
     * @param orderForm
     * @return int
     * @author huangguilong
     */
    @Transactional
    @Override
    public int add(OrderForm orderForm) throws BusinessException {
        orderForm.setCreateTime(new Date());
        String newOderId = getNewOrderIdRedis();
        orderForm.setOrderId(newOderId);
        // 补充数据库中当前订单货物的订单编号
        orderGoodsDao.updateOrderId(newOderId);
        // 补充数据库中当前订单费用的订单编号
        orderFeeDao.updateOrderId(newOderId);
        int n=0;
        // 捕获订单编号重复异常
        try {
            n = orderFormDao.insertSelective(orderForm);
        } catch (Exception e) {
            // 若订单号重复抛出自定义异常
            throw new BusinessException("订单编号为："+newOderId+"，请重新提交或重启服务器");
        }
        return n;
    }

    /**
     * 利用redis获取新增订单编号
     * @return String
     * @author huangguilong
     */
    private String getNewOrderIdRedis(){
        StringBuffer sb = new StringBuffer();
        String currentDate = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = orderIdPrefix + currentDate;
        long incr = sequenceUtil.incr(key, 1);  //设置每次自增的步长为1
        System.out.println(key);
        System.out.println(incr);
        String code = SequenceUtil.getSequence(incr, 4);  //数字顺序编号长度4
        return sb.append(key).append(code).toString();
    }

    /**
     * 编辑委托订单
     * @param orderForm
     * @return int
     * @author huangguilong
     */
    @Override
    public int edit(OrderForm orderForm) {
        orderForm.setUpdateTime(new Date());
        return orderFormDao.updateByPrimaryKeySelective(orderForm);
    }

    /**
     * 删除委托订单
     * @param orderForm
     * @return int
     * @author huangguilong
     */
    @Transactional
    @Override
    public int remove(OrderForm orderForm) {
        //删除订单货物
        orderGoodsDao.deleteAllByOrderId(orderForm.getOrderId());
        //删除订单费用
        orderFeeDao.deleteAllByOrderId(orderForm.getOrderId());
        return orderFormDao.deleteByPrimaryKey(orderForm.getId());
    }

    /**
     * 根据客户获取委托订单
     * @param orderForm
     * @return PageInfo<OrderForm>
     * @author wanglu
     */
    @Override
    public PageInfo<OrderForm> getByCustomer(OrderForm orderForm) {
        PageHelper.startPage(orderForm.getPageNum(), orderForm.getPageSize());
        List<OrderForm> orderFormList = orderFormDao.getByCustomer(orderForm);
        return new PageInfo<OrderForm>(orderFormList);
    }

    /**
     * 查询当日新增委托单数量
     * @return int
     * @author 张荣颜
     */
    @Override
    public int getTodayAddQuantity() {
        return orderFormDao.getTodayAddQuantity();
    }

    /**
     * 查询最近一年,每个月的订单数量
     * @return List<OrderForm>
     * @author 张荣颜
     */
    @Override
    public List<OrderForm> getChangeOfOrderQuantityYear() {
        return orderFormDao.getChangeOfOrderQuantityYear();
    }

    /**
     * 查询未完成的订单数量
     * @return int
     * @author 张荣颜
     */
    @Override
    public int getOrderUnfinishedQuantity() {
        return orderFormDao.getOrderUnfinishedQuantity();
    }

    /**
     * 查询各个城市的订单数量与货重
     * @return List<OrderForm>
     * @author 张荣颜
     */
    @Override
    public List<OrderForm> getCityOrderWeight() {
        return orderFormDao.getCityOrderWeight();
    }

    /**
     * 查询已经结算货款与未结算货款
     * @return List<Map>
     * @author 张荣颜
     */
    @Transactional
    @Override
    public List<Map> getIncomeStatus() {
        List<Map> mapList=new ArrayList<>();
        Map<String,Object> map1=new HashMap<>();
        Map<String,Object> map2=new HashMap<>();
        //已收
       Double amountReceivable=orderFormDao.getAmountReceivable();
        //未收
        Double amountNotReceivable=orderFormDao.getAmountNotReceivable();
        map1.put("value",amountReceivable);
        map1.put("name","已收");
        map2.put("value",amountNotReceivable);
        map2.put("name","未收");
        mapList.add(map1);
        mapList.add(map2);
        return mapList;
    }

    /**
     * 查询当前调度单未被派发的订单
     * @param id
     * @return List<OrderForm>
     * @author chenpeng
     */
    @Override
    public List<OrderForm> listByDispatch(Integer id) {
        return orderFormDao. listByDispatch(id);
    }

    /**
     * 获取送达图片
     * @param finishImg
     * @return String
     * @author chenpeng
     */
    @Override
    public String getImg(String finishImg) {
        if(!StringUtils.hasLength(finishImg)) {
            return "";
        }
        File file = new File(imgPath + finishImg);
        if(file.exists()){
            return getImgBase(imgPath + finishImg);
        }
        return "";
    }

    /**
     * 查询近六个月订单
     * @return List<OrderForm>
     * @author 张荣颜
     */
    @Override
    public List<OrderForm> getChangeOfOrderQuantitySixMonths() {
        return orderFormDao.getChangeOfOrderQuantitySixMonths();
    }

    /**
     * 查询近一个月订单
     * @return List<OrderForm>
     * @author 张荣颜
     */
    @Override
    public List<OrderForm> getChangeOfOrderQuantityOneMonth() {
        return orderFormDao.getChangeOfOrderQuantityOneMonth();
    }
}
